package io.gitee.chearnee.fw.web.interceptor;

import io.gitee.chearnee.fw.web.util.FwAsserts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.annotation.Annotation;

/**
 * 过时Api
 *
 * @author yangzhi
 * @Date 2021/11/16 17:15
 **/
@Slf4j
public class ForceLowApiBlockInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
          throws Exception {
    if (!(handler instanceof HandlerMethod method)) {
      return true;
    }
    Class<?> clazz = method.getBeanType();
    boolean flag = getFlag(clazz, method, Deprecated.class);
    if (flag) {
      log.info("低版本接口->{}", request.getRequestURI());
      FwAsserts.fail("当前应用版本较低，请使用新接口进行访问");
    }
    return true;
  }

  /**
   * 获取注解标识
   *
   * @param clazz
   * @param method
   * @param annotationClass
   * @return
   */
  private boolean getFlag(Class<?> clazz, HandlerMethod method,
                          Class<? extends Annotation> annotationClass) {
    //作用于方法上
    Annotation ignoreReturnLogMethod = method.getMethodAnnotation(annotationClass);
    //作用于类上
    Annotation ignoreReturnLogClass = clazz.getAnnotation(annotationClass);
    return null != ignoreReturnLogMethod || null != ignoreReturnLogClass;
  }
}
